package com.ellfors.common.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ellfors.common.ext.emitOnScope
import com.ellfors.common.http.entity.BaseResponse
import com.ellfors.common.http.utils.CoroutinesManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow

abstract class BaseViewModel : ViewModel() {

    //是否在加载中
    val isLoading = MutableStateFlow(false)

    //用于没有Data的Http结果返回 1.是否成功 2.code 3.msg
    val httpResult = MutableSharedFlow<Triple<Boolean, Int, String>>()

    /**
     * 显示加载中
     */
    fun showLoading() {
        isLoading.emitOnScope(viewModelScope, true)
    }

    /**
     * 隐藏加载中
     */
    fun dismissLoading() {
        isLoading.emitOnScope(viewModelScope, false)
    }

    /**
     * 请求成功，用于没有Data的返回
     *
     * @param code Int
     */
    fun httpSuccess(code: Int = 0) {
        httpResult.emitOnScope(viewModelScope, Triple(true, code, ""))
    }

    /**
     * 请求失败，用于没有Data的返回
     *
     * @param code Int
     * @param msg String?
     */
    fun httpFailure(code: Int = 0, msg: String? = "") {
        httpResult.emitOnScope(viewModelScope, Triple(false, code, msg ?: ""))
    }

    /**
     * 异步请求，自己订阅回调
     */
    fun <T> requestHttp(block: suspend CoroutineScope.() -> BaseResponse<T>) =
        CoroutinesManager.launch(viewModelScope) { block() }

    /**
     * 同步请求，需要开启协程作用域
     * 用于只需要处理结果，不需要处理异常
     * 或者同时请求多个接口，统一处理数据，此时需要自己调用async{}，接收处调用await()
     */
    suspend fun <T> getHttpResult(block: suspend () -> BaseResponse<T>) =
        CoroutinesManager.getHttResult { block() }
}